package com.kintreda.tools.upload;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.kintreda.common.config.exception.CommonBaseErrorCode;
import com.kintreda.common.config.exception.CommonBaseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

/**
 * 阿里云OSS
 */
@Component
public class AliyunOssUtils {

    @Value("${upload.aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${upload.aliyun.accessKeySecret}")
    private String accessKeySecret;
    @Value("${upload.aliyun.endpoint}")
    private String endpoint = "http://oss-cn-chengdu.aliyuncs.com";
    @Value("${upload.aliyun.bucket}")
    private String bucketName = "nowhappy-static";
    private static String[] fileSuffix = {"jpg", "bmp", "jpeg", "png", "gif","mp4","3gp","webm","flv","mkv","doc","docx","xls","xlsx","pdf"};


    public String upload(MultipartFile file) {
        //判断图片是否为空
        if (file.isEmpty()) {
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_IS_EMPTY);
        }
        // 判断是否是合法的文件后缀
        int dotPos = file.getOriginalFilename().lastIndexOf(".");
        if (dotPos < 0) {
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_FORMAT_ERROR);
        }
        String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
        boolean flag = false;
        for (String s : fileSuffix) {
            if (s.equals(fileExt)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_FORMAT_ERROR);
        }
        //判断文件大小
        if (file.getSize() > 30 * 1024 * 1024) {
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_OVERSIZE);
        }
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            String path = "upload/"+ LocalDate.now()+"/";
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String key = path+UUID.randomUUID().toString().replaceAll("\\-", "")+'.'+fileExt;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new ByteArrayInputStream(file.getBytes()));
            // 上传文件。
            ossClient.putObject(putObjectRequest);
            // 关闭OSSClient。
            ossClient.shutdown();
            return endpoint.replace("http://", "http://" + bucketName+ ".")+"/"+key;
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_FAIL);
        }
    }

    /**
     * 直接上传byte
     * @param data
     * @return
     */
    public String uploadByByte(byte[] data) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String path = "upload/"+ LocalDate.now()+"/";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = path+UUID.randomUUID().toString().replaceAll("\\-", "");
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new ByteArrayInputStream(data));
        // 上传文件。
        ossClient.putObject(putObjectRequest);
        // 关闭OSSClient。
        ossClient.shutdown();
        return endpoint.replace("http://", "http://" + bucketName+ ".")+"/"+key;
    }

}
